
#import "SquareViewController.h"

@interface  SquareViewController()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tvList;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger list_count;
@property (nonatomic, assign) NSInteger page_count;
@end

@implementation SquareViewController

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [_tvList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"广场";
    // Do any additional setup after loading the view.
    [self.view addSubview:self.tableView];
    _list_count = 0;
    _page_count = 1;
    for (NSDictionary *dict in [self arrayDataSource]) {
        SquareModel *model = [SquareModel new];
        model.userPic = dict[@"user_pic"];
        model.userName = dict[@"user_name"];
        model.publicTime = dict[@"public_time"];
        model.content = dict[@"content"];
        model.imgCount = [dict[@"img_count"] integerValue];
        model.commentCount = dict[@"comment_count"];
        model.img = dict[@"img"];
        model.contentId = dict[@"contentId"];
        model.LikeNum = [dict[@"LikeNum"] integerValue ];
        model.CommentNum = [dict[@"CommentNum"] integerValue];
        model.title = dict[@"title"];
        [self.dataSource addObject:model];
        _list_count++;
    }
    _page_count++;
    [_tvList reloadData];
    
    //下拉刷新
    __weak typeof(self) weakVC = self;
    [weakVC.tvList addPullToRefreshWithActionHandler:^{
        [weakVC refreshAction];
        [weakVC performSelector:@selector(stopRefreshAnimation) withObject:nil afterDelay:1];
    }];
    
    [self.tvList addInfiniteScrollingWithActionHandler:^{
        [weakVC requestDataStart: [NSString stringWithFormat:@"%ld",weakVC.list_count]];
        [weakVC performSelector:@selector(stopUpRefreshAnimation) withObject:nil afterDelay:2];
    }];
    [self.tvList triggerInfiniteScrolling];
}


// 下拉刷新
-(void)refreshAction{
    self.dataSource = NULL;
    _list_count = 0;
    _page_count = 1;
    for (NSDictionary *dict in [self arrayDataSource]) {
        SquareModel *model = [SquareModel new];
        model.userPic = dict[@"user_pic"];
        model.userName = dict[@"user_name"];
        model.publicTime = dict[@"public_time"];
        model.content = dict[@"content"];
        model.imgCount = [dict[@"img_count"] integerValue];
        model.commentCount = dict[@"comment_count"];
        model.img = dict[@"img"];
        model.contentId = dict[@"contentId"];
        model.LikeNum = [dict[@"LikeNum"] integerValue ];
        model.CommentNum = [dict[@"CommentNum"] integerValue];
        model.title = dict[@"title"];
        [self.dataSource addObject:model];
        _list_count++;
//        NSLog(@"xiala: %lu", _list_count);
    }
    _page_count++;
    [_tvList reloadData];
}

//停止下拉刷新
-(void)stopRefreshAnimation{
    [_tvList.pullToRefreshView stopAnimating];
}

-(void)stopUpRefreshAnimation {
    [_tvList.infiniteScrollingView stopAnimating];
}

- (void)requestDataStart:(NSString*)start {
    for (NSDictionary *dict in [self arrayDataSource]) {
        SquareModel *model = [SquareModel new];
        model.userPic = dict[@"user_pic"];
        model.userName = dict[@"user_name"];
        model.publicTime = dict[@"public_time"];
        model.content = dict[@"content"];
        model.imgCount = [dict[@"img_count"] integerValue];
        model.commentCount = dict[@"comment_count"];
        model.img = dict[@"img"];
        model.contentId = dict[@"contentId"];
        model.LikeNum = [dict[@"LikeNum"] integerValue ];
        model.CommentNum = [dict[@"CommentNum"] integerValue];
        model.title = dict[@"title"];
        [self.dataSource addObject:model];
        _list_count++;
//        NSLog(@"shangla: %lu", _list_count);
    }
    _page_count++;
    [_tvList reloadData];
}

#pragma mark - TableView
-(UITableView *)tableView{
    if (!_tvList) {
        _tvList = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tvList.delegate = self;
        _tvList.dataSource = self;
        _tvList.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tvList.backgroundColor = [UIColor whiteColor];
    }
    return _tvList;
}

#pragma mark - TableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ident = @"Cell";
    SquareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (!cell) {
        cell = [[SquareTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
    }
    SquareModel *model = self.dataSource[indexPath.section];
    [cell setModel:model];
    
    return cell;
    
}

#pragma mark - TableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat height = [SquareTableViewCell hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
        
        SquareTableViewCell *regCell = (SquareTableViewCell *)sourceCell;
        // 配置数据
        SquareModel *model = self.dataSource[indexPath.section];
        [regCell setModel:model];
        
    } cache:^NSDictionary *{
        
        return @{kHYBCacheUniqueKey: [NSString stringWithFormat:@"%ld",indexPath.section],
                 kHYBCacheStateKey : @"cell",
                 // 如果设置为YES，若有缓存，则更新缓存，否则直接计算并缓存s
                 // 主要是对社交这种有动态评论等不同状态，高度也会不同的情况的处理
                 kHYBRecalculateForStateKey : @(NO) // 标识要重新更新
                 };
        
    }];
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

#pragma mark - 数据源
-(NSArray *)arrayDataSource{
    __block NSMutableDictionary *jsonDictionaryOrArray = [[NSMutableDictionary alloc] init];
    NSString *front_url = @"http://172.18.178.56/api/content/public?page=";
    NSString *page_url = [NSString stringWithFormat:@"%lu", _page_count];
    NSString *end_url = @"&eachPage=3";
    NSString *urlString = [[front_url stringByAppendingString:page_url] stringByAppendingString:end_url];
    NSURL *url = [NSURL URLWithString:urlString];
    // here, you will clear all cookies.
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSError *jsonError;
        jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
        if(jsonError) {
            // check the error description
            NSLog(@"json error : %@", [jsonError localizedDescription]);
        } else {
            if ([jsonDictionaryOrArray[@"State"] isEqual: @"success"]) {

            }
        }
        dispatch_semaphore_signal(semaphore);
    }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    NSArray *items = [jsonDictionaryOrArray valueForKeyPath:@"Data"];
    NSMutableArray *jsonResult = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < items.count; i++) {
        NSMutableDictionary *tempjson = [[NSMutableDictionary alloc] init];
        tempjson[@"user_pic"] = @"";
        NSString *temp_user_name = [[[items objectAtIndex:i] objectForKey:@"User"] valueForKeyPath:@"Name"];
        tempjson[@"user_name"] = temp_user_name;
        NSNumber *temp_public_time_n = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"PublishDate"];
        NSString *temp_public_time_s = [[NSString alloc] initWithFormat:@"%@", temp_public_time_n];
        NSTimeInterval time = [temp_public_time_s doubleValue];
        NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time/1000];
        NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        [formatter setTimeZone:timeZone];
        NSString *temp_public_time = [formatter stringFromDate:detaildate];
        tempjson[@"public_time"] = temp_public_time;
        NSString *temp_title = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"Name"];
        tempjson[@"title"] = temp_title;
        NSString *temp_content = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"Detail"];
        tempjson[@"content"] = temp_content;
        NSArray *temp_img = [[[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"Album"]valueForKeyPath:@"Images"];
        NSInteger temp_img_count_i = temp_img.count;
        NSNumber *temp_img_count = [[NSNumber alloc] initWithInteger:temp_img_count_i];
        tempjson[@"img_count"] = temp_img_count;
        NSNumber *temp_likenum = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"LikeNum"];
        tempjson[@"LikeNum"] = temp_likenum;
        NSNumber *temp_commentnum = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"CommentNum"];
        tempjson[@"CommentNum"] = temp_commentnum;
        NSMutableArray *temp_uiimage_set = [[NSMutableArray alloc] init];
        for (NSInteger j = 0; j < temp_img_count_i; ++j) {
            NSString *before_url = @"http://172.18.178.56/api/thumb/";
            NSString *img_url = [temp_img[j] valueForKeyPath:@"Thumb"];
            NSString *all_url = [before_url stringByAppendingString:img_url];
            NSURL *imageURL = [NSURL URLWithString:all_url];
            NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
            UIImage *temp_uiimage = [UIImage imageWithData:imageData];
            NSLog(@"temp_uiimage: %@", temp_uiimage);
            [temp_uiimage_set addObject:temp_uiimage];
        }
        tempjson[@"img"] =temp_uiimage_set;
        NSString *temp_content_id = [[[items objectAtIndex:i] objectForKey:@"Data"] valueForKeyPath:@"ID"];
        tempjson[@"contentId"] = temp_content_id;
        tempjson[@"comment_count"] = @[];
        [jsonResult addObject:tempjson];
    }
    return jsonResult;
}

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    InfdetailsViewController *detailVC = [[InfdetailsViewController alloc] init];
    SquareModel *model = self.dataSource[indexPath.section];
    NSString *content_id = model.contentId;
    [detailVC viewDidLoad: content_id];
    [self.navigationController pushViewController:detailVC animated:NO];
}

@end
